/**
 * Created by IntelliJ IDEA.
 * User: akolonitsky
 * Date: 2/10/12
 * Time: 12:07 PM
 * To change this template use File | Settings | File Templates.
 */
package org.kolonitsky.alexey
{
    import mx.formatters.Formatter;

    import org.kolonitsky.alexey.utils.DateUtil;

    [ResourceBundle("common")]

    public class LocaleDateFormatter extends Formatter
    {
        public var isShort:Boolean = true;

        public function LocaleDateFormatter()
        {
            super();
        }




        //---------------------------------------------------------------------
        //
        //  Override formatter API
        //
        //---------------------------------------------------------------------

        override public function format(value:Object):String
        {
            var prefix:String = isShort ? "short" : "full";
            var format:String = resourceManager.getString("common", prefix + "-date-format");
            if (format == null || format.length == 0)
                return "";

            var date:Date = new Date(value);
            var size:int = 0;

            if (DateUtil.compare(date, DateUtil.TODAY, DateUtil.MILISECONDS_PER_DAY) == 0)
                return resourceManager.getString("common", "today");

            if (DateUtil.compare(date, DateUtil.YESTERDAY, DateUtil.MILISECONDS_PER_DAY) == 0)
                return resourceManager.getString("common", "yesterday");

            if (DateUtil.compare(date, DateUtil.TOMORROW, DateUtil.MILISECONDS_PER_DAY) == 0)
                return resourceManager.getString("common", "tomorrow");

            var day:Array = format.match(/D+/ig);
            if (day && day.length)
            {
                size = String(day[0]).length;
                format = format.replace(/D+/ig, date.date);
            }

            var month:Array = format.match(/M+/ig);
            if (day && day.length)
            {
                size = String(month[0]).length <= 3 ? 1 : 2;
                var str:String = resourceManager.getString("common", "m" + size + "-" + date.month);
                format = format.replace(/M+/ig, str);
            }

            if (isShort)
                return format;

            var year:Array = format.match(/Y+/ig);
            if (day && day.length)
            {
                size = String(year[0]).length;
                format.replace(/Y+/ig, date.fullYear);
            }

            return format;
        }
    }
}
